package com.ztom.v2;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhangTao
 */
public class Code47ConstructBinaryTreeFromPreorderAndInorderTraversal {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        Map<Integer, Integer> index = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            index.put(inorder[i], i);
        }
        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, index);
    }

    public TreeNode buildTree(int[] preorder, int pl, int pr, int[] inorder, int il, int ir, Map<Integer, Integer> index) {
        if (pl > pr || il > ir) {
            return null;
        }
        // 先序第一个节点就是 root
        TreeNode root = new TreeNode(preorder[pl]);
        // 对应中序的位置
        int inIndex = index.get(root.val);
        // 左子树节点
        int lCount = inIndex - il;
        // 先序左子树范围: [pl + 1, pl + lCount], 对应中序范围: [il, inIndex - 1]
        root.left = buildTree(preorder, pl + 1, pl + lCount, inorder, il, inIndex - 1, index);
        // 先序右子树范围: [pl + lCount + 1, pr], 对应中序范围: [inIndex + 1, ir]
        root.right = buildTree(preorder, pl + lCount + 1, pr, inorder, inIndex + 1, ir, index);
        return root;
    }
}
